package com.bckj.fastboot.core.extra.increment;

import com.bckj.fastboot.core.redis.RedisOps;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;

@RequiredArgsConstructor
public class IncrOps {

    @Value("${fastboot.incr.prefix:'commons:incr:'}")
    private String prefix;

    private final RedisOps redisOps;

    /**
     * 递增
     * @param key key
     * @param delta 增量
     * @return 值
     */
    public long incr(String key, long delta) {
        return incr(key, delta, 0);
    }

    /**
     * 递增
     * @param key key
     * @param delta 增量
     * @param baseValue 基本值
     * @return 值
     */
    public long incr(String key, long delta, long baseValue) {
        key = prefix + key;
        if (redisOps.hasKey(key)) {
            return redisOps.incr(key, delta);
        } else {
            if (baseValue != 0) {
                return redisOps.incr(key, baseValue);
            } else {
                return redisOps.incr(key, delta);
            }
        }
    }

    /**
     * 通过 lua 脚本实现增量
     *
     * @param script 脚本
     * @param key key
     * @return value
     */
    public long scriptIncr(String script,String key) {
        key = prefix + key;
        return redisOps.incrLongLuaScript(script, key);
    }
}
